var assert = require('chai').assert;
var request = require('request');
var config = require('../app/config/config.js');
var Q = require('q');

var showDebug = true;
var debug = (typeof showDebug !== 'undefined') ? console.log.bind(console) : function() {};

var httpBaseUrl = 'http://localhost:' + config.http.port + config.http.baseUrl;
suite('test api/v1/orgnization', function() {
	var __url = httpBaseUrl + '/v1/orgnization';
	var aItem = {
		"name": "root",
		"description": "总部",
		"path": []
	};

	var aItem2 = {
		"name": "foo",
		"description": "foo",
		"path": []
	};

	var aItem3 = {
		"name": "bar",
		"description": "bar",
		"path": []
	};

	function ajaxPost(url, json, cb) {
		request({
			method: 'POST',
			url: url,
			body: json,
			json: true,
			headers: {
				"content-type": "application/json"
			}
		}, function(err, res, body) { // body is object
			if (err) throw err;
			cb(err, res);
		});
	}

	function createOrg(parent, json, done) {
		if (parent) {
			json.path = parent.path.concat(parent._id);
		}
		ajaxPost(__url, json, function(err, res) {
			var body = res.body;
			// debug(body);
			assert.equal(res.statusCode, 200);
			var code = body.errCode;
			assert.isTrue(code === 0 || code === 2500); // 2500 = orgnization exists
			done(err, body);
		});
	}

	test('[x] create orgnization', function(done) {
		createOrg(null, aItem, function(err, result) {
			var code1 = result.errCode;
			if (result.errCode === 2500)
				return done();

			createOrg(result.result, aItem2, function(err2, result2) {
				var code2 = result2.errCode;
				if (code2 === 2500)
					return done();

				createOrg(result2.result, aItem3, function(err2, result3) {
					var code3 = result3.errCode;
					orgId = result3.result._id;
					done();
				});
			});
		});
	});



	var orgId;
	var __url2 = httpBaseUrl + '/v1/orgnization/vendors';

	function updateVendor(json, done) {
		ajaxPost(__url2, json, function(err, res) {
			var body = res.body;
			// debug(body);
			assert.equal(res.statusCode, 200);
			var code = body.errCode;
			assert.isTrue(code === 0);
			done(err, body);
		});
	}


	test('[x] update orgnization vendors', function(done) {
		setTimeout(function() {
			json1.orgnization = orgId;
			json2.orgnization = orgId;
			json3.orgnization = orgId;
			updateVendor(json1, function(errA, resA) {
				updateVendor(json2, function(errB, resB) {
					updateVendor(json3, function(errC, resC) {
						done();
					});
				});
			});
		}, 200);
	});

	var json1 = {
		orgnization: orgId,
		vendors: {
			set: ["1", "2", "3"]
		}
	};
	var json2 = {
		orgnization: orgId,
		vendors: {
			add: ["5", "6", "7"]
		}
	}
	var json3 = {
		orgnization: orgId,
		vendors: {
			remove: ["1", "2", "7"]
		}
	}
});